package service

import (
	"encoding/json"
	"errors"
	"fmt"
	"git.inedcn.com/ined/cmn"
	"math/rand"
	constant "rongyy/src/constants"
	"rongyy/src/middlewares"
	"strconv"
	"strings"
	"time"

	"rongyy/src/models"
)

type RegistrationService struct {
}

func (pc *RegistrationService) GetBranch() ([]models.BranchModel, error) {
	sm := &models.RegisterModel{}
	data, err := sm.GetBranch()
	if err != nil {
		return nil, fmt.Errorf("获取数据失败")
	}
	return data, err
	//data := make([]models.BranchModel, 2)
	//data[0] = models.BranchModel{
	//	Id:       2,
	//	HospName: "航天院区",
	//	Address:  "成都市锦江区静明路377号（三环路航天立交桥内侧）",
	//	Mobile:   "028-64369122(传染)",
	//	Mobile1:  "028-85571931/028-84521550(结核)",
	//	Des:      "设置有结核科、肝病科、感染性疾病科、皮肤科、妇产科、儿科、外科(胸外、普外、肛肠、泌尿、骨科、耳鼻咽喉头颈外科)、内科(传染病合并内科疾病)、中西医结合科、中医科、血液透析中心、寄生虫、药学门诊。",
	//}
	//data[1] = models.BranchModel{
	//	Id:       1,
	//	HospName: "净居寺院区",
	//	Address:  "成都市锦江区净居寺路18号",
	//	Mobile1:  "",
	//	Des:      "设置有急诊科、肝病科、外科（胸外、骨科、普外、肛肠、耳鼻咽喉头颈外科）、内科（内一科、内二科）、口腔科、妇产科、儿科、消化疾病、营养科。",
	//}
	//return data, nil
}

func (pc *RegistrationService) GetPatInfo(req *models.Req3300Params) (*models.Resp3300, error) {
	data, err := (&HisService{}).GetPatInfo(req)
	if err != nil {
		middlewares.Logger.Println("Unmarshal resp3013 failed ", err)
		return nil, err
	}
	return data, nil
}

func (pc *RegistrationService) QueryDepartment(id int64) (*models.Resp1012, error) {
	hangtian := make([]string, 0)
	jingju := make([]string, 0)
	hangtian = append(hangtian, "276", "350", "119", "120", "121", "122", "123", "124", "136",
		"138",
		"139",
		"140",
		"141",
		"142",
		"150",
		"502", "509", "507", "508",
		"143", "145", "146", "147", "353", "269", "125", "365", "367", "153", "268", "324", "149", "352", "349", "151", "351", "368", "474", "361", "432", "152", "492")

	//
	jingju = append(jingju,
		"479",
		"480",
		"481",
		"195",
		"363",
		"131",
		"322",
		"199",
		"128",
		"364",
		"366",
		"130",
		//"133",
		//"398",
		"129",
		"477",
		//"413",
		"482",
		//"134",
		"398",
		"503",
	)
	data, err := (&HisService{}).QueryDepartment()
	fmt.Println(data)
	if err != nil {
		middlewares.Logger.Println("Unmarshal resp3013 failed ", err)
		return nil, err
	}
	if id == 1 {
		depts := make([]models.Department, 0)
		for _, item := range data.Departments {
			bool := isExist(item.DepartmentCode, jingju)
			if bool {
				depts = append(depts, item)
			}
		}
		data.Departments = depts
	}

	if id == 2 {
		depts := make([]models.Department, 0)
		for _, item := range data.Departments {
			bool := isExist(item.DepartmentCode, hangtian)
			if bool {
				depts = append(depts, item)
			}
		}
		data.Departments = depts
	}

	return data, nil
}

func isExist(num string, nums []string) bool {
	for _, n := range nums {
		if n == num {
			return true
		}
	}
	return false
}

func (pc *RegistrationService) QueryDoctor(dptCode string) (interface{}, error) {
	data, err := (&HisService{}).QueryDoctor(dptCode)
	if err != nil {
		middlewares.Logger.Println("Unmarshal resp3013 failed ", err)
		return nil, err
	}
	return data, nil
}

func (pc *RegistrationService) QueryAdmSchedule(req *models.Req1004Params) ([]models.Schedule, error) {
	data, err := (&HisService{}).QueryAdmSchedule(req)
	if err != nil {
		middlewares.Logger.Println("Unmarshal resp3013 failed ", err)
		return nil, err
	}
	list := make([]models.Schedule, 0)
	for _, r := range data {
		if !strings.Contains(r.DoctorSessType, "免费号") && !strings.Contains(r.DoctorSessType, "急诊") {
			doct, has, _ := (&models.DoctorModel{}).GetDoctorForReg(r.DoctorCode)
			if has {
				r.DoctorImg = doct.NewImage
				r.DoctorDesc = doct.Descript
			}
			list = append(list, r)
		}
	}
	return list, nil
}

func (pc *RegistrationService) QueryScheduleTimeInfo(scheduleItemCode string) (interface{}, error) {
	data, err := (&HisService{}).QueryScheduleTimeInfo(scheduleItemCode)
	if err != nil {
		middlewares.Logger.Println("Unmarshal resp3013 failed ", err)
		return nil, err
	}
	return data, nil
}

func (pc *RegistrationService) RegReserve(req *models.Req1005Params) (interface{}, error) {
	data, err := (&HisService{}).QueryOrder(req)
	if err != nil {
		middlewares.Logger.Println("Unmarshal resp3013 failed ", err)
		return nil, err
	}
	return data, nil
}

func (pc *RegistrationService) QueryScheduleTimeInfoRange(req *models.ReqScheduleTimeInfoRange) (interface{}, error) {
	if len(req.Codes) == 1 {
		data1, err := (&HisService{}).QueryScheduleTimeInfo(req.Codes[0])
		if err != nil {
			middlewares.Logger.Println("Unmarshal resp3013 failed ", err)
			return nil, err
		}
		return data1, nil
	}

	if len(req.Codes) == 2 {
		data1, err := (&HisService{}).QueryScheduleTimeInfo(req.Codes[0])
		if err != nil {
			middlewares.Logger.Println("Unmarshal resp3013 failed ", err)
			return nil, err
		}

		data2, err := (&HisService{}).QueryScheduleTimeInfo(req.Codes[1])
		if err != nil {
			middlewares.Logger.Println("Unmarshal resp3013 failed ", err)
			return nil, err
		}
		list := make([]models.TimeRange, len(data1)+len(data2))
		copy(list, data1)
		copy(list[len(data1):], data2)
		return list, err
	}
	return nil, fmt.Errorf("只能传1-2个code")
}

func (pc *RegistrationService) LockOrder(req *models.Req10015Params) (interface{}, error) {
	data, err := (&HisService{}).LockOrder(req)
	if err != nil {
		middlewares.Logger.Println("LockOrder 10015 failed ", err)
		return nil, err
	}
	if data.ResultCode != "0" {
		return nil, errors.New(data.ResultContent)
	}
	//挂号成功，入库
	reg := &models.RegisterModel{
		OrderSn:          "",
		Fee:              data.RegFee,
		PatientId:        req.PatientId,
		RegInfo:          models.RegInfo{},
		LockInfo:         models.LockInfo{},
		RefundSn:         "",
		HisTradeNo:       "",
		AdmNo:            "",
		Status:           "locked",
		PayStatus:        "",
		UpdatedBy:        "",
		CreatedAt:        cmn.JsonTime{},
		UpdatedAt:        cmn.JsonTime{},
		Hospital:         "",
		Remark:           "",
		HisFeedback:      "",
		HisCode:          "",
		LockQueueNo:      data.LockQueueNo,
		ScheduleItemCode: data.ScheduleItemCode,
		AdmDoc:           data.AdmDoc,
		AdmDate:          data.AdmDate,
		AdmTime:          data.AdmTime,
		TransactionId:    data.TransactionId,
		DeptName:         req.DeptName,
		DoctorName:       req.DoctorName,
		PatientName:      req.PatientName,
	}
	err = reg.Create(reg)
	if err != nil {
		middlewares.Logger.Println("reg create 10015 failed ", err)
		return nil, err
	}
	return data, nil
}

func (pc *RegistrationService) UnLockOrder(req *models.Req10016Params) (interface{}, error) {
	rm := models.RegisterModel{}
	reg, has, err := rm.FindByTransactionId(req.TransactionId)
	if !has {
		return nil, fmt.Errorf("订单信息错误")
	}
	current := time.Now().Unix()
	t, err := time.ParseInLocation("2006-01-02 15:04:05", reg.UpdatedAt.String(), time.Local)
	if err != nil {
		return nil, err
	}
	diff := current - t.Unix()
	if reg.PayStatus == "paying" && diff < 60 {
		return nil, fmt.Errorf("订单正在支付中，请1分钟后重试")
	}
	if reg.PayStatus == "paid" || reg.Status == "confirm" {
		return nil, fmt.Errorf("订单已支付成功")
	}
	data, err := (&HisService{}).UnLockOrder(req)
	if err != nil {
		middlewares.Logger.Println("Unmarshal resp3013 failed ", err)
		return nil, err
	}
	reg1 := &models.RegisterModel{
		TransactionId: req.TransactionId,
		Status:        "unlocked",
	}
	err = reg1.UnlockReg()
	if err != nil {
		middlewares.Logger.Println("UnlockReg failed ", err)
		return nil, err
	}
	return data, nil
}

func (pc *RegistrationService) Register(req *models.Req1101Params) (*models.Resp1101, error) {
	if len(req.TransactionId) < 5 {
		return nil, fmt.Errorf("入参有误")
	}
	regOrder, has, err := (&models.RegisterModel{}).FindByTransactionId(req.TransactionId)
	data := &models.Resp1101{}
	if err != nil {
		constant.RecordSnMap.Delete(req.TransactionId + req.PatientID)
		return nil, fmt.Errorf("查询订单tid错误")
	}
	if !has {
		constant.RecordSnMap.Delete(req.TransactionId + req.PatientID)
		return nil, fmt.Errorf("订单不存在")
	}
	if regOrder.Status == "confirm" && regOrder.PayStatus == "paid" {
		constant.RecordSnMap.Delete(req.TransactionId + req.PatientID)
		return nil, fmt.Errorf("挂号订单已确认成功")
	}

	_, ok := constant.RecordSnMap.Load(req.TransactionId + req.PatientID)
	if !ok {
		if regOrder.Status == "locked" && regOrder.PayStatus == "paying" {
			constant.RecordSnMap.Store(req.TransactionId+req.PatientID, req.TransactionId+req.PatientID)
			data, err = (&HisService{}).Register(req)

			if err != nil {
				middlewares.Logger.Println("Unmarshal resp3013 failed ", err)
				constant.RecordSnMap.Delete(req.TransactionId + req.PatientID)
				// 超时支付，自动退费
				if data.ResultContent == "该号超时未支付,已被系统自动失效,请尝试重新生成订单." {
					float64Value, _ := strconv.ParseFloat(regOrder.Fee, 64)
					refundReq := &models.RefundReq{
						Id:         7,
						ReturnCode: "refund_sn",
						OrderSn:    regOrder.OrderSn,
						RefundFee:  float64Value,
						BusiType:   "reg",
					}
					middlewares.Logger.Println("自动退费==", refundReq)
					refundResp, err := (&PaymentService{}).Refund(refundReq)
					if err != nil || !refundResp.IsSuccess {
						return nil, fmt.Errorf("挂号超时，自动退费失败")
					}
					if refundResp.Data.ReturnCode == "000000" {
						reg := &models.RegisterModel{
							OrderSn:   regOrder.OrderSn,
							RefundSn:  "refundResp.Data.CustId",
							PayStatus: "refunded",
							Remark:    "超时自动退费",
						}
						reg.UpdateRefund()
					}
				}
				return nil, err
			}

			reg := &models.RegisterModel{
				TransactionId: req.TransactionId,
				Status:        "confirm",
				PayStatus:     "paid",
				AdmNo:         data.AdmNo,
				AdmitAddress:  data.AdmitAddress,
				TimeRange:     data.TimeRange,
				HisTradeNo:    data.HisTradeOrderId,
				AdmitRange:    data.AdmitRange,
				SeqCode:       data.SeqCode,
				UpdatedBy:     req.UpdateBy,
			}
			err = reg.ConfirmReg()
			go func() {
				reqMsg := &models.ReqNoticeParams{
					OpenId:          regOrder.Openid,
					OrderId:         regOrder.OrderSn,
					PatName:         regOrder.PatientName,
					DocName:         regOrder.DoctorName,
					PatHospitalId:   regOrder.PatientId,
					DepartmentName:  regOrder.DeptName,
					AppointmentTime: data.AdmitRange,
					//Memo:            "航天院区就诊患者，可由东三环路五段辅路东南门（2号门）/静明路辅路南门（1号门）进入",
					Memo: "",
				}
				if strings.Contains(regOrder.DeptName, "净居") {
					reqMsg.Memo = ""
				}
				middlewares.Logger.Println("发送消息入参", reqMsg)
				err = (&WxNoticeService{}).RegSuccessNotice(reqMsg)
				if err != nil {
					middlewares.Logger.Println("发送消息错误", err)
				}
			}()
			constant.RecordSnMap.Delete(req.TransactionId + req.PatientID)
		} else {
			return nil, fmt.Errorf("订单状态错误")
			constant.RecordSnMap.Delete(req.TransactionId + req.PatientID)
		}

	}

	//data, err := (&HisService{}).Register(req)
	//
	//if err != nil {
	//	middlewares.Logger.Println("Unmarshal resp3013 failed ", err)
	//	return nil, err
	//}
	//reg := &models.RegisterModel{
	//	TransactionId: req.TransactionId,
	//	Status:        "confirm",
	//	PayStatus:     "paid",
	//	AdmNo:         data.AdmNo,
	//	AdmitAddress:  data.AdmitAddress,
	//	TimeRange:     data.TimeRange,
	//	HisTradeNo:    data.HisTradeOrderId,
	//	AdmitRange:    data.AdmitRange,
	//	SeqCode:       data.SeqCode,
	//	UpdatedBy:     req.UpdateBy,
	//}
	//err = reg.ConfirmReg()

	//middlewares.Logger.Println("发送消息入参=====", regOrder)
	// 就医助手---挂号成功
	//go func() {
	//	reqMsg := &models.ReqNoticeParams{
	//		OpenId:          regOrder.Openid,
	//		OrderId:         regOrder.OrderSn,
	//		PatName:         regOrder.PatientName,
	//		DocName:         regOrder.DoctorName,
	//		PatHospitalId:   regOrder.PatientId,
	//		DepartmentName:  regOrder.DeptName,
	//		AppointmentTime: regOrder.AdmitRange,
	//	}
	//	middlewares.Logger.Println("发送消息入参", reqMsg)
	//	err = (&WxNoticeService{}).RegSuccessNotice(reqMsg)
	//	if err != nil {
	//		middlewares.Logger.Println("发送消息错误", err)
	//	}
	//}()
	return data, nil
}

func (pc *RegistrationService) RegisterZJ(req *models.Req1101Params) (*models.Resp1101, error) {
	if len(req.AppOrderCode) == 0 {
		return nil, errors.New("appOrderCode不得为空")
	}
	regData, has, err := (&models.RegisterModel{}).FindOrderByAppOrderCode(req.AppOrderCode)
	if err != nil {
		middlewares.Logger.Println("FindOrderByAppOrderCode failed ", err, req)
		return nil, err
	}
	if !has {
		return nil, fmt.Errorf("订单不存在")
	}
	if regData.Status == "confirm" && regData.PayStatus == "paid" {
		return nil, fmt.Errorf("订单已支付并确认完成")
	}
	if regData.Status == "locked" && regData.PayStatus == "paying" {
		fmt.Println(regData)
		data, err := (&HisService{}).Register(req)
		if err != nil {
			middlewares.Logger.Println("诊间挂号确认失败 RegisterZJ failed ", err, req)
			return nil, err
		}
		reg := &models.RegisterModel{
			Status:       "confirm",
			PayStatus:    "paid",
			AdmitAddress: data.AdmitAddress,
			TimeRange:    data.TimeRange,
			HisTradeNo:   data.HisTradeOrderId,
			AdmitRange:   data.AdmitRange,
			SeqCode:      data.SeqCode,
			UpdatedBy:    req.UpdateBy,
			AppOrderCode: req.AppOrderCode,
			AdmNo:        data.AdmNo,
		}
		err = reg.ConfirmZjyy()
		if err != nil {
			middlewares.Logger.Println("诊间挂号插入失败 failed ", err, req)
			return nil, err
		}
		return data, nil
	}
	return nil, fmt.Errorf("订单状态错误")
}

func (pc *RegistrationService) QueryAdmOPReg(req *models.Req1104Params) (*models.Resp1104, error) {
	data, err := (&HisService{}).QueryAdmOPReg(req)
	if err != nil {
		middlewares.Logger.Println("Unmarshal resp3013 failed ", err)
		return nil, err
	}
	return data, nil
}

func (pc *RegistrationService) OPRegReturn(req *models.Req1003Params) (*models.Resp1003, error) {
	data, err := (&HisService{}).OPRegReturn(req)
	if err != nil {
		middlewares.Logger.Println("Unmarshal resp3013 failed ", err)
		return nil, err
	}
	reqHis := &models.RegisterModel{}
	orders, has, err := reqHis.FindByAdmNo(req.AdmNo)
	if err != nil {
		middlewares.Logger.Println("RefundFromHis FindByAdmNo  failed ", err)
		return nil, err
	}
	if !has {
		return nil, errors.New("订单不存在")
	}
	if orders.Status != "confirm" && orders.Status != "paid" {
		return nil, errors.New("订单状态错误")
	}
	// 退钱，这里要分一卡通，微信支付，医保
	refundSn := ""
	refundFee := 0.0
	if orders.PayWay == "ykt" {
		// 去查
		yktData, err := (&models.YktOrdersModel{}).FindByOrderSn(orders.OrderSn)
		if err != nil {
			middlewares.Logger.Println("一卡通订单错误")
			return nil, err
		}
		f, err := strconv.ParseFloat(orders.Fee, 64)
		reqYkt := &models.YktRefundReq{
			MchOrderId:   yktData.MchOrderId,
			PayOrderId:   yktData.PayOrderId,
			RefundAmount: f * 100,
			MchRefundId:  "yjtrefund" + yktData.PayOrderId,
			RefundReason: "患者自助退费",
		}
		jsonData, err := json.Marshal(reqYkt)
		if err != nil {
			middlewares.Logger.Println("挂号退费错误1 failed==", err)
			return nil, errors.New("一卡通 挂号订单金额转换失败")
		}
		yktRefundResp, err := (&YktService{}).Refund(string(jsonData), "88800100009")
		refundSn = yktRefundResp.MchRefundId
	} else if orders.PayWay == "xyjy" {
		//xyjyPat, err := (&models.PatientXyjyModel{}).Get(orders.PatientId)
		//if err != nil {
		//	middlewares.Logger.Println("xyjy订单错误")
		//	return nil, err
		//}

		//patInfo, _, err := (&models.CardModel{}).FindByPatientId(orders.PatientId)
		//if err != nil {
		//	middlewares.Logger.Println("xyjy FindByPatientId订单错误")
		//	return nil, err
		//}
		reqXyjy := &models.XyjyRefundReqModel{
			AppId:          "appohmjy202410160014",
			MyPrivateKey:   "00e72d0e068ba799259e35f882611423a49dbbcad0a33c74ddf5dfbfc88096b441",
			ApigwPublicKey: "04a33690cec47663b70cbff54e073ab135e04133a0e100e3f5b8e9d5c2c1e1d66e9326026a283900584cdf87bac9740f565229fcb60c8f420fda036a2aacd03422",
			RefundId:       "refund" + orders.OrderSn,
			PayId:          orders.OrderSn,
			RefundFee:      orders.Fee,
		}

		middlewares.Logger.Println("reqXyjy====", reqXyjy)
		xyjyRefund, _ := (&XyjyService{}).Refund(reqXyjy)
		refundSn = xyjyRefund.RefundId
	} else {
		// 微信退费
		f, err := strconv.ParseFloat(orders.Fee, 64)
		if err != nil {
			fmt.Println("转换失败：", err)
			return nil, errors.New("挂号订单金额转换失败")
		}
		refundReq := &models.RefundReq{
			Id:         constant.MerchantId,
			ReturnCode: "refund_sn",
			OrderSn:    orders.OrderSn,
			RefundFee:  f,
			BusiType:   "reg",
		}
		resp, err := (&PaymentService{}).Refund(refundReq)
		if !resp.IsSuccess {
			middlewares.Logger.Println("挂号退费错误1 failed==", resp)
			return nil, errors.New(resp.Msg)
		}
		if resp.Data.ReturnCode != "000000" {
			middlewares.Logger.Println("挂号退费错误2 failed==", resp)
			return nil, errors.New(resp.Data.ReturnMsg)
		}
		refundSn = resp.Data.CustId
		refundFee = resp.Data.TxInfo.Amount
	}

	orders.PayStatus = "refunded-patient"
	orders.RefundSn = refundSn
	orders.InvoiceStr = data.CanclePrtRid
	orders.Remark = "患者自助退费"
	err = orders.UpdateRefund()
	if err != nil {
		middlewares.Logger.Println("reg UpdateRefund failed", orders.OrderSn, err)
	}

	hrm := &models.RefundModel{
		OrderSn:   orders.OrderSn,
		RefundSn:  refundSn,
		RefundFee: refundFee,
		Remark:    "患者自助退费",
	}
	err = hrm.Create()
	if err != nil {
		middlewares.Logger.Println("reg HisRefundModel create failed", orders.OrderSn, err)
	}

	// 回写his
	reqCallBackHis := &models.RegisterModel{
		Fee:        orders.Fee,
		PatientId:  orders.PatientId,
		OrderSn:    data.HisTradeNo,
		InvoiceStr: data.CanclePrtRid,
	}
	_, err = (&HisService{}).SaveSelfRefundInfo(reqCallBackHis)
	if err != nil {
		middlewares.Logger.Println("退费回写his", orders.OrderSn, orders.AdmNo, orders.InvoiceStr, err)
	}
	middlewares.Logger.Println("退费回写his成功", orders.OrderSn, orders.AdmNo, orders.InvoiceStr, err)

	// 就医助手---取消挂号成功通知
	go func() {
		reqMsg := &models.ReqNoticeParams{
			OpenId:          orders.Openid,
			OrderId:         orders.PatientId + time.Now().String(),
			PatName:         orders.PatientName,
			DocName:         orders.DoctorName,
			PatHospitalId:   orders.PatientId,
			DepartmentName:  orders.DeptName,
			AppointmentTime: orders.TimeRange,
		}
		middlewares.Logger.Println("发送消息入参", reqMsg)
		err = (&WxNoticeService{}).CancelRegNotice(reqMsg)
		if err != nil {
			middlewares.Logger.Println("发送消息错误", err)
		}
	}()
	return data, nil
}

func (pc *RegistrationService) LockOrderList(req *models.RegisterModel) ([]models.RegisterModel, int64, error) {
	data, total, err := (&models.RegisterModel{}).LockOrderList(req.PatientId)
	if err != nil {
		middlewares.Logger.Println("Unmarshal resp3013 failed ", err)
		return nil, 0, err
	}
	return data, total, nil
}

func (pc *RegistrationService) PayRegister(req *models.RegisterModel, ip string) (*models.PaymentRespData, string, error) {
	data, has, err := (&models.RegisterModel{}).FindByTransactionId(req.TransactionId)
	if !has {
		return nil, "", errors.New("订单不存在")
	}
	//// 查看订单是否超时
	current := time.Now().Format("2006-01-02 15:04:05")
	currentT, err := time.Parse("2006-01-02 15:04:05", current)
	if err != nil {

	}
	regTime, _ := time.Parse("2006-01-02 15:04:05", data.CreatedAt.String())
	if (currentT.Unix() - regTime.Unix()) > 610 {
		return nil, "", errors.New("订单已超时，请重新挂号")
	}

	if data.Status != "locked" || data.PayStatus != "" {
		return nil, "", errors.New("订单状态错误")
	}

	rand.Seed(time.Now().UnixNano())
	t := rand.Intn(10000)
	ts := strconv.FormatInt(time.Now().UnixMicro(), 10)
	orderSn := "R" + ts + strconv.Itoa(t)
	fee, err := strconv.ParseFloat(data.Fee, 10)

	//先入库
	reg := &models.RegisterModel{
		OrderSn:       orderSn,
		RegInfo:       models.RegInfo{},
		LockInfo:      models.LockInfo{},
		PayStatus:     "paying",
		CreatedAt:     cmn.JsonTime{},
		UpdatedAt:     cmn.JsonTime{},
		TransactionId: req.TransactionId,
		Openid:        req.Openid,
		PayWay:        "wx",
	}
	middlewares.Logger.Println("reg.Paying 入参===", reg)
	err = reg.Paying()
	if err != nil {
		middlewares.Logger.Println("挂号支付中入库错误 failed ", err)
		return nil, "", err
	}
	reqPay := &models.PaymentReq{
		MerchantId: constant.MerchantId,
		Desc:       req.TransactionId,
		PayStatus:  "unpaid",
		OutTradeNo: req.TransactionId,
		TotalFee:   fee,
		ClientIp:   ip,
		BusiType:   "reg",
		OrderSn:    orderSn,
		PayWay:     constant.PayWay,
		OpenId:     req.Openid,
	}
	payResp, err := (&PaymentService{}).Pay(reqPay)
	if err != nil {
		middlewares.Logger.Println("银行调用支付返回失败1", err)
		return nil, "", err
	}
	if payResp.ERRCODE != "000000" {
		middlewares.Logger.Println("银行调用支付返回失败2", payResp)
		//请求支付成功,入库
		reg := &models.RegisterModel{
			OrderSn:       orderSn,
			RegInfo:       models.RegInfo{},
			LockInfo:      models.LockInfo{},
			PayStatus:     "paying-fail",
			CreatedAt:     cmn.JsonTime{},
			UpdatedAt:     cmn.JsonTime{},
			TransactionId: req.TransactionId,
			Openid:        req.Openid,
			Remark:        payResp.ERRMSG,
		}
		middlewares.Logger.Println("reg.Paying 入参===", reg)
		err = reg.PayingFail()
		//if err != nil {
		//	middlewares.Logger.Println("挂号支付中入库错误 failed ", err)
		//	return nil, "", err
		//}
		return nil, "", errors.New(payResp.ERRMSG)
	}
	return payResp, orderSn, err
}

// 诊间预约使用
func (pc *RegistrationService) PayRegisterZjyy(req *models.RegisterModel, ip string) (*models.PaymentRespData, string, error) {
	data, has, err := req.FindOrderByAppOrderCode(req.AppOrderCode)
	if err != nil {
		middlewares.Logger.Println("Unmarshal resp3013 failed ", err)
		return nil, "", err
	}
	if has && data.Status == "confirm" && data.PayStatus == "paid" {
		return nil, "", errors.New("订单状态错误")
	}

	rand.Seed(time.Now().UnixNano())
	t := rand.Intn(10000)
	ts := strconv.FormatInt(time.Now().UnixMicro(), 10)
	orderSn := "R" + ts + strconv.Itoa(t)
	fee, err := strconv.ParseFloat(req.Fee, 10)
	reqPay := &models.PaymentReq{
		MerchantId: constant.MerchantId,
		Desc:       req.AppOrderCode,
		PayStatus:  "unpaid",
		OutTradeNo: req.AppOrderCode,
		TotalFee:   fee,
		ClientIp:   ip,
		BusiType:   "reg",
		OrderSn:    orderSn,
		PayWay:     constant.PayWay,
		OpenId:     req.Openid,
	}
	middlewares.Logger.Println("reqPay failed ", err)
	payResp, err := (&PaymentService{}).Pay(reqPay)
	if err != nil {
		middlewares.Logger.Println("Unmarshal resp3013 failed ", err)
		return nil, "", err
	}
	if payResp.ERRCODE != "000000" {
		return nil, "", errors.New(payResp.ERRMSG)
	}
	//请求支付成功,入库
	reg := &models.RegisterModel{
		OrderSn:      orderSn,
		RegInfo:      models.RegInfo{},
		LockInfo:     models.LockInfo{},
		PayStatus:    "paying",
		CreatedAt:    cmn.JsonTime{},
		UpdatedAt:    cmn.JsonTime{},
		AppOrderCode: req.AppOrderCode,
		Openid:       req.Openid,
		Status:       "locked",
		Fee:          req.Fee,
		PatientId:    req.PatientId,
	}
	err = reg.Create(reg)
	if err != nil {
		middlewares.Logger.Println("挂号支付(预约)中入库错误 failed ", err)
		return nil, "", err
	}
	return payResp, orderSn, err
}

// QueryAdmDoctorsByName
//
//	@Description: 按患者名称查询第一个接口
//	@receiver pc
//	@param req
//	@return interface{}
//	@return error
func (pc *RegistrationService) QueryAdmDoctorsByName(req *models.Req1004Params) (interface{}, error) {
	local, _ := time.LoadLocation("Asia/Shanghai")
	req.StartDate = time.Now().In(local).Format("2006-01-02")
	data, err := (&HisService{}).QueryAdmSchedule(req)
	req.StartDate = time.Now().In(local).AddDate(0, 0, 1).Format("2006-01-02")
	req.EndDate = time.Now().In(local).AddDate(0, 0, 7).Format("2006-01-02")

	data1, err := (&HisService{}).QueryAdmSchedule(req)

	list := make([]models.Schedule, len(data)+len(data1))
	//list = append(list, data1)
	copy(list, data)
	copy(list[len(data):], data1)
	if err != nil {
		middlewares.Logger.Println("Unmarshal resp3013 failed ", err)
		return nil, err
	}
	doctorlist := make([]models.RespScheduleByName, 0)
	for _, doc := range list {
		sn := doc.DoctorCode
		doctorInfo, has, _ := (&models.DoctorModel{}).GetDoctorForReg(sn)
		d := &models.RespScheduleByName{
			DoctorName:     doc.DoctorName,
			DepartmentCode: doc.DepartmentCode,
			DepartmentName: doc.DepartmentName,
			RegFee:         doc.Fee,
			DoctorSessType: doc.DoctorSessType,
		}
		if has {
			d.Img = doctorInfo.NewImage
			d.Desc = doctorInfo.Descript
		}
		bool := false
		for i := 0; i < len(doctorlist); i++ {
			if doctorlist[i].DepartmentCode == doc.DepartmentCode && doctorlist[i].DoctorName == doc.DoctorName {
				bool = !bool
			}
		}
		if !bool {
			doctorlist = append(doctorlist, *d)
		}
	}
	return doctorlist, nil
}

// QueryAdmScheduleByName
//
//	@Description: 按患者名称查询第2个接口,查排班
//	@receiver pc
//	@param req
//	@return interface{}
//	@return error
func (pc *RegistrationService) QueryAdmScheduleByName(req *models.Req1004Params) (interface{}, interface{}, interface{}, error) {
	//req.StartDate = time.Now().In(local).Format("2006-01-02")
	//req.StartDate = time.Now().In(local).Format("2006-01-02")
	reqFirst := &models.Req1004Params{}
	reqFirst.DoctorName = req.DoctorName
	reqFirst.StartDate = req.StartDate
	reqFirst.EndDate = req.StartDate
	reqFirst.DepartmentCode = req.DepartmentCode
	data, err := (&HisService{}).QueryAdmSchedule(reqFirst)
	//req.StartDate = time.Now().In(local).AddDate(0, 0, 1).Format("2006-01-02")
	//req.EndDate = time.Now().In(local).AddDate(0, 0, 7).Format("2006-01-02")
	middlewares.Logger.Println("data====", data)
	data1, err := (&HisService{}).QueryAdmSchedule(req)

	list := make([]models.Schedule, len(data)+len(data1))
	//list = append(list, data1)
	copy(list, data)
	copy(list[len(data):], data1)
	if err != nil {
		middlewares.Logger.Println("Unmarshal resp3013 failed ", err)
		return nil, nil, nil, err
	}

	dateList := make([]string, 0)
	for _, doc := range list {
		bool1 := false
		for i := 0; i < len(dateList); i++ {
			if doc.ServiceDate == dateList[i] {
				bool1 = !bool1
			}
		}
		if !bool1 {
			dateList = append(dateList, doc.ServiceDate)
		}
	}
	return data, list, dateList, nil
}

func (pc *RegistrationService) CancelPaying(req *models.RegisterModel) error {
	data, has, err := (&models.RegisterModel{}).FindByTransactionId(req.TransactionId)
	if !has {
		return errors.New("订单不存在")
	}

	if data.PayStatus != "paying" {
		return errors.New("订单状态错误")
	}
	reg := &models.RegisterModel{
		PayStatus:     "cancelled",
		TransactionId: req.TransactionId,
	}
	middlewares.Logger.Println("reg.Paying 入参===", reg)
	err = reg.CancelPaying()
	if err != nil {
		middlewares.Logger.Println("挂号支付中入库错误 failed ", err)
		return err
	}
	return err
}

func (pc *RegistrationService) FindByOrderSn(sn string) (*models.RegisterModel, error) {
	data, has, err := (&models.RegisterModel{}).FindByOrderSn(sn)
	if err != nil {
		middlewares.Logger.Println("FindByOrderSn failed ", err)
		return nil, err
	}
	if !has {
		return nil, errors.New("订单不存在")
	}

	return data, err
}

func (pc *RegistrationService) Dbz() error {
	list, total, err := (&models.RegisterModel{}).Dbz()
	if err != nil {
		middlewares.Logger.Println("FindByOrderSn failed ", err)
		return err
	}
	if total > 0 {
		for _, item := range list {
			middlewares.Logger.Println(item.OrderSn)
			float64Value, _ := strconv.ParseFloat(item.Fee, 64)
			refundReq := &models.RefundReq{
				Id:         7,
				ReturnCode: "refund_sn",
				OrderSn:    item.OrderSn,
				RefundFee:  float64Value,
				BusiType:   "reg",
			}
			resp, _ := (&PaymentService{}).Refund(refundReq)
			if resp.Data.ReturnCode == "000000" {
				reg := &models.RegisterModel{
					OrderSn:   item.OrderSn,
					RefundSn:  resp.Data.CustId,
					PayStatus: "refunded",
					Remark:    "批量退费",
				}
				reg.UpdateRefund()
			}
		}
	}

	return nil
}

// 天府市民云专用
func (pc *RegistrationService) OPTfRegReturn(req *models.Req1003Params) (*models.Resp1003, error) {
	data, err := (&HisService{}).OPRegReturn(req)
	if err != nil {
		middlewares.Logger.Println("Unmarshal resp3013 failed ", err)
		return nil, err
	}
	reqHis := &models.RegisterModel{}
	orders, has, err := reqHis.FindByAdmNo(req.AdmNo)
	if err != nil {
		middlewares.Logger.Println("RefundFromHis FindByAdmNo  failed ", err)
		return nil, err
	}
	if !has {
		return nil, errors.New("订单不存在")
	}
	if orders.Status != "confirm" && orders.Status != "paid" {
		return nil, errors.New("订单状态错误")
	}
	// 退钱

	trade, err := (&TianfuService{}).RefundTrade(orders.OrderSn, orders.Fee)

	if trade.ResultCode == "SUCCESS" && trade.ReturnCode == "SUCCESS" {
		orders.Remark = "患者自助退费-天府-退费成功"
		orders.RefundSn = trade.RefundId
		float64Value, _ := strconv.ParseFloat(orders.Fee, 64)
		hrm := &models.RefundModel{
			OrderSn:   orders.OrderSn,
			RefundSn:  trade.TransactionId,
			RefundFee: float64Value,
			Remark:    "患者自助退费-天府",
		}
		err = hrm.Create()
	} else {
		orders.Remark = "患者自助退费-天府-退费失败"
		orders.RefundSn = "fail"
	}

	orders.PayStatus = "refunded-patient"
	orders.InvoiceStr = data.CanclePrtRid
	err = orders.UpdateRefund()
	if err != nil {
		middlewares.Logger.Println("reg UpdateRefund failed", orders.OrderSn, err)
	}
	if err != nil {
		middlewares.Logger.Println("reg HisRefundModel create failed", orders.OrderSn, err)
	}

	// 回写his
	reqCallBackHis := &models.RegisterModel{
		Fee:        orders.Fee,
		PatientId:  orders.PatientId,
		OrderSn:    data.HisTradeNo,
		InvoiceStr: data.CanclePrtRid,
	}
	_, err = (&HisService{}).SaveSelfRefundInfo(reqCallBackHis)
	if err != nil {
		middlewares.Logger.Println("退费回写his", orders.OrderSn, orders.AdmNo, orders.InvoiceStr, err)
	}
	middlewares.Logger.Println("退费回写his成功", orders.OrderSn, orders.AdmNo, orders.InvoiceStr, err)
	return data, nil
}

func (pc *RegistrationService) ChangeRegOrderPaying(req *models.RegisterModel) error {
	reg := &models.RegisterModel{
		OrderSn:       req.OrderSn,
		PayStatus:     "paying",
		TransactionId: req.TransactionId,
		PayWay:        req.PayWay,
	}
	middlewares.Logger.Println("reg.Paying 入参===", reg)
	err := reg.Paying()
	if err != nil {
		middlewares.Logger.Println("挂号支付中入库错误 failed ", err)
		return err
	}
	return err
}

func (pc *RegistrationService) PayRegisterXyzf(req *models.RegisterModel, ip string) (*models.Resp1101, string, error) {
	data, has, err := (&models.RegisterModel{}).FindByTransactionId(req.TransactionId)
	if !has {
		return nil, "", errors.New("订单不存在")
	}
	//// 查看订单是否超时
	current := time.Now().Format("2006-01-02 15:04:05")
	currentT, err := time.Parse("2006-01-02 15:04:05", current)
	if err != nil {

	}
	regTime, _ := time.Parse("2006-01-02 15:04:05", data.CreatedAt.String())
	if (currentT.Unix() - regTime.Unix()) > 610 {
		return nil, "", errors.New("订单已超时，请重新挂号")
	}

	if data.Status != "locked" || data.PayStatus != "" {
		return nil, "", errors.New("订单状态错误")
	}

	rand.Seed(time.Now().UnixNano())
	t := rand.Intn(10000)
	ts := strconv.FormatInt(time.Now().UnixMicro(), 10)
	orderSn := "R" + ts + strconv.Itoa(t)
	//fee, err := strconv.ParseFloat(data.Fee, 10)

	// 查看是否满足余额要求
	ag, err := (&models.PatientXyjyModel{}).Get(req.PatientId)
	if err != nil {
		middlewares.Logger.Println("信用挂号数据不存在 failed ", err)
		return nil, "", err
	}
	reqCheck := &models.XyjyReqModel{
		PayId:       orderSn,
		PayFee:      data.Fee,
		AgreementNo: ag.AgreementNo,
		Nme:         "",
		IdNo:        "",
		BillNo:      "",
		NotifyUrl:   "",
		PatientId:   "",
	}
	respCheck, err := (&XyjyService{}).Check(reqCheck)
	middlewares.Logger.Println("信用额度==== ", respCheck)
	if respCheck.Success && respCheck.LimitFlg != "0" {
		return nil, "", fmt.Errorf("信用余额不足")
	}
	//先入库
	reg := &models.RegisterModel{
		OrderSn:       orderSn,
		RegInfo:       models.RegInfo{},
		LockInfo:      models.LockInfo{},
		PayStatus:     "paying",
		CreatedAt:     cmn.JsonTime{},
		UpdatedAt:     cmn.JsonTime{},
		TransactionId: req.TransactionId,
		Openid:        req.Openid,
		PayWay:        "xyjy",
	}
	middlewares.Logger.Println("reg.Paying 入参===", reg)
	err = reg.Paying()
	if err != nil {
		middlewares.Logger.Println("挂号支付中入库错误 failed ", err)
		return nil, "", err
	}
	pat, _, err := (&models.CardModel{}).FindByPatientId(req.PatientId)

	reqPay1 := &models.XyjyReqModel{
		PayId:       orderSn,
		PayFee:      data.Fee,
		AgreementNo: ag.AgreementNo,
		Nme:         pat.RealName,
		IdNo:        pat.IdNo,
		BillNo:      orderSn,
		NotifyUrl:   "",
		PatientId:   req.PatientId,
	}
	middlewares.Logger.Println("信用就医支付请求======", reqPay1)
	payResp, err := (&XyjyService{}).Pay(reqPay1)
	if err != nil {
		middlewares.Logger.Println("信用就医支付失败1======", err)
		return nil, "", err
	}

	if !payResp.Success {
		middlewares.Logger.Println("信用就医支付失败2======", payResp)
		//请求支付成功,入库
		reg := &models.RegisterModel{
			OrderSn:       orderSn,
			RegInfo:       models.RegInfo{},
			LockInfo:      models.LockInfo{},
			PayStatus:     "paying-fail",
			CreatedAt:     cmn.JsonTime{},
			UpdatedAt:     cmn.JsonTime{},
			TransactionId: req.TransactionId,
			Openid:        req.Openid,
			Remark:        payResp.RspMsg,
			PayWay:        "xyjy",
		}
		middlewares.Logger.Println("reg.Paying 入参===", reg)
		err = reg.PayingFail()
		UnLockOrderReq := &models.Req10016Params{
			ScheduleItemCode: data.ScheduleItemCode,
			TransactionId:    data.TransactionId,
			LockQueueNo:      data.LockQueueNo,
		}
		data, err := (&RegistrationService{}).UnLockOrder(UnLockOrderReq)
		middlewares.Logger.Println("reg.Paying 入参===", err)
		middlewares.Logger.Println("信用就医UnLockOrder resp===", data)
		return nil, "", errors.New(payResp.RspMsg)
	}

	if payResp.Success && payResp.PaySts == "SUCCESS" && payResp.PayFee == data.Fee {
		reqConfirm := &models.Req1101Params{
			TransactionId:    req.TransactionId,
			ScheduleItemCode: data.ScheduleItemCode,
			PatientID:        req.PatientId,
			PayModeCode:      "",
			PayFee:           data.Fee,
			QueueNo:          "",
			PayAmt:           data.Fee,
			PlatformNo:       orderSn,
			OutPayNo:         "",
			PayChannel:       "",
			POSPayStr:        "",
			PayDate:          "",
			PayTime:          "",
			UpdateBy:         "",
			AppOrderCode:     "",
		}
		respConfirm, err := pc.Register(reqConfirm)
		if err != nil {
			middlewares.Logger.Println("信用就医支付 确认挂号失败3======", err)
			return nil, "", err
		}
		return respConfirm, "", nil
	}
	return nil, "", fmt.Errorf("信用就医支付失败")
}
